package com.soft.small.app.service.deviceControl;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.soft.small.app.entity.AppClient;
import com.soft.small.app.service.BaseService;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.internal.wire.MqttWireMessage;

@Slf4j
public class SmartLight extends BaseService {
    private final static String model = "deviceControl";
    private AppClient appClient;

    public SmartLight(AppClient appClient) {
        this.appClient = appClient;
    }

    /**
     *设备控制
     * @param deviceId
     * @param properties
     * @return
     */
    public String control(int deviceId, String properties)  {
        String payload = "{\"sn\":\"\",\"deviceId\":204,\"properties\":{},\"userUnique\":\"\",\"controlSources\":\"user\",\"controlSourcesIdentity\":\"\"}";
        JSONObject payloadJson = JSONUtil.parseObj(payload);
        payloadJson.put("sn", appClient.getSn());
        payloadJson.put("deviceId", deviceId);
        payloadJson.put("properties", JSONUtil.parseObj(properties));
        payloadJson.put("userUnique", appClient.getUserUnique());
        payloadJson.put("controlSourcesIdentity", appClient.getUserUnique());

        MqttWireMessage message = publishToHost(appClient, model, model, payloadJson.toString());
        try {
            log.info("客户端接收到的消息id是：{}\n消息header是：{}\n消息内容是:******{}",message.getMessageId(),message.getHeader(),message.getPayload());
        } catch (MqttException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 异常控制
     *
     * @param data
     * @return
     */
    public String abnormalControl(String data) {
        publishToHost(appClient, model, model, data);
        return null;
    }
}
